package com.letcoding.spiderAutoHome.api.service.impl;

import com.letcoding.spiderAutoHome.api.service.AutoHomeApiService;
import com.letcoding.spiderAutoHome.job.CloseHttpConnectionJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.parser.Entity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Service
@Slf4j
public class AutoHomeApiServiceImpl implements AutoHomeApiService {
    @Autowired
    private PoolingHttpClientConnectionManager connectionManager;
    @Override
    public String getHtml(String url) {
        //1.使用连接池管理器获取连接
        CloseableHttpClient httpClient = HttpClients.custom ().setConnectionManager (connectionManager).build ();
        //2.创建http请求
        HttpGet httpGet = new HttpGet (url);
        CloseableHttpResponse httpResponse = null;
        String html = null;
        try {
            //发起请求
            httpResponse =httpClient.execute (httpGet);
            //判断请求是否成功
            if(httpResponse != null  && httpResponse.getStatusLine ().getStatusCode () == 200){
            //判断是否有响应体
                if(httpResponse.getEntity () != null){
                    html = EntityUtils.toString (httpResponse.getEntity (), Charsets.UTF_8);
                    return html;
                }
            }
        } catch (IOException e) {
            e.printStackTrace ();
            log.error ("获取汽车至今信息异常", e);
        }finally {
            if (httpResponse != null){
                try {
                    httpResponse.close ();
                } catch (IOException e) {
                    e.printStackTrace ();
                    log.error ("获取汽车之家信息响应关闭异常",e);
                }
            }
        }
        return null;
    }

    @Override
    public String getImage(String url) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = null;
        String fileName = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            // 判断请求是否成功
            if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
                // 判断是否有响应体
                if (httpResponse.getEntity() != null) {
                    // 如果有响应体，则进行解析
                    String contentTypeVal = httpResponse.getFirstHeader("Content-Type").getValue();
                    if(contentTypeVal.contains("image/")){
                        String extName =  contentTypeVal.split("/")[1];
                        fileName = UUID.randomUUID().toString().replace("-","") + "." + extName;
                        OutputStream os = new FileOutputStream (new File ("D:/23项目复习/第一阶段/排序算法/autohome-image/" + fileName));
                        httpResponse.getEntity().writeTo(os);
                        return fileName;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("获取汽车之家评测图片异常：{}", e);
        }finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("获取汽车之家评测图片响应关闭异常：{}", e);
                }
            }
        }
        return null;
    }
}
